<template>
    <div class="main_box" style="padding:10px">
        <div class="add_wrap">
            <el-row>
                <div class="tit">
                    <h2>{{ dataForm.activeId ? '编辑活动' : '新增活动' }}</h2>
                    <el-button type="success" plain size="small" icon="fa fa-mail-forward"
                        @click="returnList">返回</el-button>
                </div>
                <el-form :model="dataForm" ref="dataForm" label-width="200px" :rules="rules">
                    <el-row>
                        <el-form-item prop="activeType" label="活动类型">
                            <el-radio v-model="dataForm.activeType" :label="1">店铺活动</el-radio>
                            <el-radio v-model="dataForm.activeType" :label="2">缴费活动</el-radio>
                        </el-form-item>
                        <el-form-item prop="activeName" label="活动名称">
                            <el-input v-model="dataForm.activeName"></el-input>
                        </el-form-item>

                        <el-form-item prop="businessId" label="商户">
                            <el-select v-model="dataForm.businessId" clearable filterable>
                                <el-option v-for="item in businessList" :value="item.id" :label="item.name" :key="item.id">
                                </el-option>>
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="maxCount" label="单次购买可享活动价的产品总数" v-if="dataForm.activeType == 1">
                            <el-input v-maxnum="{ obj: dataForm, key: 'maxCount', int: true }"
                                v-model="dataForm.maxCount"></el-input>
                        </el-form-item>
                        <el-form-item label="活动时间" prop="activeTime">
                            <el-date-picker clearable v-model="dataForm.activeTime" type="datetimerange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item prop="" label="活动限制" v-if="dataForm.activeType == 1">
                            <el-select v-model="dataForm.limitType" :disabled="this.$route.query.id ? true : false">
                                <el-option v-for="item in limitTypeList" :value="item.id" :label="item.name"
                                    :key="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="activeShowName" label="活动展示名称" v-if="dataForm.activeType == 1">
                            <el-input v-model="dataForm.activeShowName"></el-input>
                        </el-form-item>
                        <el-form-item prop="activeShowUnit" label="活动展示单位(折扣)" v-if="dataForm.activeType == 1">
                            <el-input v-model="dataForm.activeShowUnit"></el-input>
                        </el-form-item>
                        <el-form-item prop="describes" label="活动描述">
                            <el-input type="textarea" v-model="dataForm.describes"></el-input>
                        </el-form-item>

                    </el-row>
                    <el-row v-show="dataForm.businessId && dataForm.activeType == 1">
                        <div class="tit">
                            <h2>活动货品列表</h2>
                            <el-button type="primary" icon="fa fa-plus" size="small" @click="handleAddBS">
                                添加货品
                            </el-button>
                        </div>
                        <el-table ref="tableList" :data="dataForm.activeServers"
                            style="max-width: fit-content;width: fit-content;">
                            <el-table-column align="center" label="操作" width="70">
                                <template slot-scope="scope">
                                    <el-button type="danger" icon="el-icon-minus" circle @click="sub(scope.$index)">

                                    </el-button>
                                </template>
                            </el-table-column>
                            <el-table-column type="index" align="center" width="50" label="序号">

                            </el-table-column>
                            <el-table-column align="center" label="货品编号" prop="serverCode" width="150"></el-table-column>
                            <el-table-column align="center" label="货品图片" width="160">
                                <template slot-scope="scope">
                                    <div class="img-wrapper">
                                        <el-image style="width: 100px;height:100px" title="点击可预览" :src="scope.row.mainImage"
                                            fit="cover" :preview-src-list="[scope.row.mainImage]" :z-index="scope.$index">
                                        </el-image>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="货品名称" prop="name" width="150">
                            </el-table-column>
                            <!-- <el-table-column align="center" label="货品分类" width="200">
                                <template slot-scope="scope">
                                    {{ scope.row.serverClassifyName }}-{{ scope.row.thirdClassifyName }}
                                </template>
                            </el-table-column> -->
                            <el-table-column align="center" label="规格">
                                <template slot-scope="scope" width="120">
                                    <el-tag type="danger" size="mini" effect="dark" v-if="scope.row.serverType == 2">
                                        套餐
                                    </el-tag>
                                    <el-tag effect="dark" size="mini" v-else-if="scope.row.variantState == 1">
                                        单品
                                    </el-tag>
                                    <el-tag type="success" size="mini" effect="dark"
                                        v-else-if="scope.row.variantState == 2">
                                        多规格
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <!-- <el-table-column align="center" label="平台原价" prop="price"></el-table-column> -->
                            <el-table-column align="center" label="平台售价(元)" prop="salePrice" width="130"></el-table-column>
                            <el-table-column align="center" label="活动价(元)" width="130">
                                <template slot-scope="scope">
                                    <el-input v-if="scope.row.variantState != 2" v-model="scope.row.activePrice"
                                        v-maxnum="{ obj: scope.row, key: 'activePrice', zero: true }">

                                    </el-input>
                                    <span v-else>#</span>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="折扣" width="100">
                                <template slot-scope="scope">
                                    <div v-if="scope.row.variantState != 2">
                                        {{ getDiscount(scope.row) }}
                                    </div>
                                    <span v-else>#</span>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="可享活动价的个数" width="100">
                                <template slot-scope="scope">
                                    <el-input v-if="scope.row.variantState != 2" v-model="scope.row.maxNum"
                                        v-maxnum="{ obj: scope.row, key: 'maxNum', int: true, max: dataForm.maxCount }">

                                    </el-input>
                                    <span v-else>#</span>
                                </template>
                            </el-table-column>

                            <el-table-column align="center" label="操作" width="150">
                                <template slot-scope="scope">
                                    <el-button v-if="scope.row.variantState == 2" type="success" plain size="mini"
                                        @click="handleVariant(scope.row)">
                                        编辑规格
                                    </el-button>
                                    <span v-else>#</span>
                                </template>
                            </el-table-column>
                            <!--
                            <el-table-column align="center" label="商户原价" prop="marketPrice"></el-table-column>
                            <el-table-column align="center" label="商户折扣比例" prop="discount"></el-table-column>
                            <el-table-column align="center" label="成本价" prop="costPrice"></el-table-column> -->
                        </el-table>
                    </el-row>

                    <el-row v-show="dataForm.activeType == 2">
                        <div class="tit">
                            <h2>缴费活动列表</h2>
                            <el-button type="primary" icon="fa fa-plus" size="small" @click="handleAddGZ">
                                添加活动规则
                            </el-button>
                        </div>
                        <el-table ref="tableGzList" :data="dataForm.activeRules" style="width: 100%;">
                            <el-table-column align="center" label="操作" width="70">
                                <template slot-scope="scope">
                                    <el-button type="danger" icon="el-icon-minus" circle @click="subGz(scope.$index)">

                                    </el-button>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="区间（月数）" width="auto">
                                <template slot-scope="scope">
                                    <el-row>
                                        <el-col :span="10">
                                            <el-input placeholder="请输入最小值"
                                                @blur="numRules(scope.row.minRange, 1, scope.$index)"
                                                v-model="scope.row.minRange" clearable
                                                :disabled="scope.$index == 0 ? false : true">
                                            </el-input>
                                        </el-col>
                                        <el-col :span="4">
                                            <div style="height: 40px;line-height: 40px;">
                                                &lt;= x &lt;
                                            </div>
                                        </el-col>
                                        <el-col :span="10"><el-input placeholder="请输入最大值"
                                                @blur="numRules(scope.row.maxRange, 2, scope.$index)"
                                                v-model="scope.row.maxRange" clearable>
                                            </el-input></el-col>
                                    </el-row>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="优惠内容" width="auto">
                                <template slot-scope="scope">
                                    <el-input placeholder="" v-model="scope.row.content" clearable>
                                    </el-input>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-row>
                    <el-row>
                        <el-form-item>
                            <el-button plain type="primary" @click="sureClick">保 存</el-button>
                            <el-button plain @click="returnList">取 消</el-button>
                        </el-form-item>
                    </el-row>
                </el-form>
            </el-row>
            <business-server-select active="1" ref="businessServerSelect" :business-id="dataForm.businessId"
                @getServerList="getCopyServerList"></business-server-select>


            <el-dialog :visible.sync="variant.show" title="规 格" center>
                <el-table :data="variant.list" max-height="600px">
                    <el-table-column align="center" width="140" label="变体">
                        <template slot-scope="scope">
                            <div>
                                {{ scope.row.sku }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="图片" width="160">
                        <template slot-scope="scope">
                            <div class="img-wrapper">
                                <el-image style="width: 100px;height:100px" title="点击可预览" :src="scope.row.mainImg"
                                    fit="cover" :preview-src-list="[scope.row.mainImg]" :z-index="scope.$index">
                                </el-image>
                            </div>
                        </template>
                    </el-table-column>

                    <el-table-column align="center" label="平台售价(元)" prop="salePrice" width="150"></el-table-column>
                    <el-table-column align="center" label="活动价(元)" width="150">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.activePrice"
                                v-maxnum="{ obj: scope.row, key: 'activePrice', zero: true }">

                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="折扣" width="150">
                        <template slot-scope="scope">
                            <div>
                                {{ getDiscount(scope.row) }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="可享活动价的个数">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.maxNum"
                                v-maxnum="{ obj: scope.row, key: 'maxNum', int: true, max: dataForm.maxCount }">
                            </el-input>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- <div slot="footer">
                    <el-button type="primary">
                        确定
                    </el-button>
                    <el-button>
                        取消
                    </el-button>
                </div> -->

            </el-dialog>

        </div>
    </div>
</template>

<script>
import * as message from "@/constants/message";
import ActiveApi from '@/api/operation/active';
import BusinessApi from "@/api/business/business";
import BusinessServerApi from "@/api/goods/businessServer";
import BusinessServerSelect from "../../components/BusinessServerSelect.vue";
export default {
    data() {
        return {
            dataForm: {
                activeId: "",
                activeName: "",
                activeShowName: "",
                activeShowUnit: "",
                describes: "",
                activeType: 1,
                businessId: "",
                maxCount: "",
                activeTime: ["", ""],
                activeServers: [],
                limitType: "",
                activeRules: []

            },
            rules: {
                activeName: [
                    { required: true, message: "请输入活动名称", trigger: "change" }
                ],
                activeType: [
                    { required: true, message: "请选择活动类型", trigger: "change" }
                ],
                activeTime: [
                    { required: true, message: "选择时间", trigger: "change" }
                ],
                /*activeShowName: [
                    { required: true, message: "请输入活动展示名称", trigger: "blur" }
                ],
                activeShowUnit: [
                    { required: true, message: "请输入活动展示单位", trigger: "blur" }
                ],
                describes: [
                    { required: true, message: "请输入活动描述", trigger: "blur" }
                ]*/
            },
            businessList: [],
            variant: {
                show: false,
                list: [],
                // specNames:[],//规格名字列表
            },
            limitTypeList: [
                { id: 1, name: "24小时内只能一次" },
                { id: 2, name: "只能买一次" },
                { id: 3, name: "只能买三次" },
            ],
        }
    },
    components: {
        BusinessServerSelect
    },
    mounted() {
        this.init()
    },
    methods: {
        async init() {
            this.getBusinessList()
            if (this.$route.query.id) {
                this.dataForm.activeId = this.$route.query.id
                this.getData()

            }
        },
        handleAddGZ() {
            console.log(this.dataForm.activeRules)
            let obj = {
                minRange: this.dataForm.activeRules.length == 0 ? '' : this.dataForm.activeRules[this.dataForm.activeRules.length - 1].maxRange,
                maxRange: '',
                content: ''
            }
            this.dataForm.activeRules.push(obj)
        },
        keydown(e) {
            if (e.keyCode == 32) {
                e.returnValue = false;
            }
        },
        numRules(val, type, index) {
            const regex = /^(0|[1-9]\d*)$/;
            if (!val) {
                return false
            }
            //type 1=修改最小值 type 2=修改最大值
            if (!regex.test(val)) {
                this.$message.error("值只能为整数")
                type == 1 ? this.dataForm.activeRules[index].minRange = '' : this.dataForm.activeRules[index].maxRange = ''
            } else {
                if (type == 1) {
                    if (index > 0) {
                        const prevMax = this.dataForm.activeRules[index - 1].maxRange;
                        if (val < prevMax) {
                            this.dataForm.activeRules[index].minRange = prevMax;
                        }
                    }
                } else {

                    if (index < this.dataForm.activeRules.length - 1) {
                        for (let i = index; i < this.dataForm.activeRules.length - 1; i++) {
                            const currentRule = this.dataForm.activeRules[i];
                            const nextRule = this.dataForm.activeRules[i + 1];
                            if (currentRule.minRange == currentRule.maxRange) {
                                currentRule.maxRange++;
                            }
                            if (nextRule.minRange < currentRule.maxRange) {
                                nextRule.minRange = currentRule.maxRange;
                                nextRule.maxRange = Number(nextRule.minRange) + 1;
                            } else if (nextRule.minRange >= currentRule.maxRange) {
                                nextRule.minRange = currentRule.maxRange;
                                if (!nextRule.maxRange || nextRule.maxRange <= nextRule.minRange) {
                                    nextRule.maxRange = Number(nextRule.minRange) + 1;
                                }
                            }
                        }
                    }
                }
            }
        },
        getData() {
            ActiveApi.getActive({
                id: this.dataForm.activeId
            }).then(res => {
                this.$Utils.bindingBean(this.dataForm, res.data)
                this.formatData(res.data)
            })
        },
        formatData(data) {
            const { dataForm } = this
            const { beginDate, endDate } = data
            dataForm.activeTime = [beginDate, endDate]
            const list = []
            const activeServers = []
            data.activeServers.forEach(item => {
                const index = list.findIndex(item2 => item2.some(item3 => item3.serverId == item.serverId))
                if (index != -1) {
                    list[index].push(item)
                } else {
                    list[list.length] = [item]
                }
            })


            list.forEach(item => {
                activeServers.push(item[0])
                if (item[0].sku && item[0].sku != '无') {
                    this.$set(item[0], "list", item)
                }
            })
            dataForm.activeServers = activeServers

        },
        // 获取商户列表
        getBusinessList() {
            BusinessApi.listIdNameVo().then(res => {
                this.businessList = res.data
            })
        },
        handleVariant(row) {
            const { variant } = this
            variant.show = true
            variant.list = row.list
            // variant.specNames = row.activeServers[0].variantSpecs.map(item=>item.specName)
        },
        getDiscount(row) {
            const { salePrice, activePrice } = row
            if (activePrice && activePrice !== 0) {
                if (activePrice == 0) {
                    row.activeDiscount = 10

                } else {
                    row.activeDiscount = parseFloat(((activePrice / salePrice) * 10).toFixed(2))
                }
                return row.activeDiscount

            }
        },
        sub(index) {
            this.dataForm.activeServers.splice(index, 1)
        },
        subGz(index) {
            if (index != 0) {
                this.maxMonth = this.dataForm.activeRules[index].minRange
            } else {
                this.maxMonth = ''
            }
            this.dataForm.activeRules.splice(index)
        },
        handleAddBS() {
            this.$refs.businessServerSelect.handleCreate()
        },
        async getCopyServerList(val) {
            let { activeServers } = this.dataForm
            const serverIds = []
            val = val.filter(item => !activeServers.some(item2 => item2.serverId == item.serverId))
            val.forEach(item => {
                if (item.variantState != 2) {
                    // 单变体
                    this.$set(item, 'activePrice', "")
                    this.$set(item, "activeDiscount", "")
                    this.$set(item, "maxNum", "")
                } else {
                    serverIds.push(item.serverId)
                }
            })
            if (serverIds.length) {
                let res = await BusinessServerApi.listServerVariant({ serverIds: serverIds.toString() })
                res = res.data
                const data = Object.keys(res)
                data.forEach(item2 => {
                    const target = val.find(item3 => item3.serverId == item2)

                    this.$set(target, "list", res[item2])

                    // console.log(target,item2,data[item2])
                    target.list.forEach(item3 => {
                        this.$set(item3, 'activePrice', "")
                        this.$set(item3, "activeDiscount", "")
                        this.$set(item3, "maxNum", "")
                    })
                })
            }

            this.dataForm.activeServers = activeServers.concat(val)
        },
        checkData() {
            let { activeServers } = this.dataForm
            this.activeServers = []
            this.dataForm.activeServers = activeServers = activeServers.filter(item => {
                // 先过滤调没有填写价格的
                if (item.variantState == 2 && item.list.some(item2 => item2.activePrice || item2.activePrice === 0)) {
                    return true
                } else if (item.variantState != 2 && (item.activePrice || item.activePrice === 0)) {
                    return true
                }
            })

            activeServers.forEach(item => {
                // item.beginDate = item.activeTime[0]
                // item.endDate = item.activeTime[1]
                let arr = []
                if (item.list) {
                    arr = item.list.filter(item2 => item2.activePrice || item2.activePrice === 0)
                        .map(item2 => ({ activePrice: item2.activePrice, maxNum: item2.maxNum, serverId: item2.serverId, sku: item2.sku, name: item.name }))

                } else {
                    arr = [{ activePrice: item.activePrice, maxNum: item.maxNum, serverId: item.serverId, sku: '无', name: item.name }]
                }
                this.activeServers = this.activeServers.concat(arr)
            })
            return true
        },
        sureClick() {
            this.$refs.dataForm.validate(valid => {
                if (valid) {
                    if (!this.checkData()) return
                    this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {})
                        .then(() => {
                            if (!this.checkData()) return
                            if (this.dataForm.activeId) {
                                this.editData();
                            } else {
                                this.addData();
                            }
                        });
                }
            })
        },
        addData() {
            let param = {
                activeName: this.dataForm.activeName,
                activeShowName: this.dataForm.activeShowName,
                activeShowUnit: this.dataForm.activeShowUnit,
                describes: this.dataForm.describes,
                activeType: this.dataForm.activeType,
                businessId: this.dataForm.businessId,
                maxCount: this.dataForm.maxCount,
                beginDate: this.dataForm.activeTime[0],
                endDate: this.dataForm.activeTime[1],
                activeServers: this.activeServers,
                limitType: this.dataForm.limitType,
                activeRules: this.dataForm.activeRules
            };
            ActiveApi.addActive(param).then(res => {
                this.$Utils.notifySuccess()
                this.returnList();
            })
        },
        editData() {
            let param = {
                activeId: this.dataForm.activeId,
                activeName: this.dataForm.activeName,
                activeShowName: this.dataForm.activeShowName,
                activeShowUnit: this.dataForm.activeShowUnit,
                describes: this.dataForm.describes,
                activeType: this.dataForm.activeType,
                businessId: this.dataForm.businessId,
                maxCount: this.dataForm.maxCount,
                beginDate: this.dataForm.activeTime[0],
                endDate: this.dataForm.activeTime[1],
                activeServers: this.activeServers,
                limitType: this.dataForm.limitType,
                activeRules: this.dataForm.activeRules
            };
            ActiveApi.editActive(param)
                .then(() => {
                    this.$Utils.notifySuccess()
                    this.returnList();
                })
        },
        returnList() {
            this.$store.dispatch('delView', this.$route);
            this.$router.push({ path: '/operation/activeManagement' });
        }
    },

}
</script>
<style lang="scss">
@import "@/assets/css/views/add.scss";
@import "@/assets/css/views/content.scss";
</style>

<style lang="scss" scoped>
.upload-img {
    &::v-deep .el-upload-dragger {
        display: flex;
        justify-content: space-around;
        align-items: center;

        .tip {
            padding-bottom: 30px;
        }
    }
}
</style>

